<template>
  <view class="goods_wrap">
    <view class="goods_page">
      <div class="bg-fff u-p-40 u-m-t-10 u-relative">
        <navigator url="/pages/address/index" class="u-flex flex-between"
                   v-if="!showAddress"
                   style="color: #101010">
          <view class="u-flex u-flex-col" style="align-items: flex-start">
            <view class="u-font-40 u-p-b-15">无收货地址，去添加</view>
            <view class="u-font-sm">{{giftName || '课程教材(赠品)'}}将邮寄至此地址</view>
          </view>
          <u-icon name="arrow-right" size="28" color="#666"></u-icon>
        </navigator>
        <navigator :url="`/pages/address/index?id=${showAddress.id}`" v-if="showAddress" class="u-flex flex-between">
          <view class="u-flex u-flex-col" style="align-items: flex-start">
            <view class="u-font-md u-p-b-15">{{showAddress.province || ''}}
              <text class="u-p-l-10">{{showAddress.street || ''}}</text>
              <text class="u-p-l-10">{{showAddress.district || ''}}</text>
            </view>
            <view class="u-font-40 u-p-b-15">{{showAddress.address}}</view>
            <view class="u-font-sm">
              {{showAddress.consignee}}<text class="u-p-l-10">{{showAddress.phone || ''}}</text>
            </view>
          </view>
          <u-icon name="arrow-right" size="28" color="#666"></u-icon>
        </navigator>
        <image src="../../static/img/line.png" style="width: 100%;height: 2px; bottom: 0;left: 0" class="u-absolute"></image>
      </div>
      <div class="row cont-center bg-fff pd_l_30 pd_r_30 pd_t_30 pd_b_30">
        <div class="left-img">
          <img v-for="(item,index) in list.goodsCovers" :key="index" v-if="index == 0" :src="item" />
        </div>
        <div class="pd_l_30">
          <div class="font-28 font-b col-333 pd_b_30">{{list.goodsName}}</div>
          <div class="font-24 col-999">规格：{{current.desc}}</div>
        </div>
      </div>
      <div class="bg-fff pd_l_30 pd_r_30 mg_t_10">
        <div class="row cont-center pd_t_30 pd_b_30 yh_bd_bottom">
          <div class="font-28 col-666 flex-1">商品金额</div>
          <div class="font-28 col-666 pd_r_10">￥{{current.price}}</div>
        </div>
        <div class="row cont-center pd_t_30 pd_b_30 yh_bd_bottom">
          <div class="font-28 col-666 flex-1">商品数量</div>
          <div class="font-28 col-666 pd_r_10">1</div>
        </div>

        <!-- 限时优惠 -->
        <div v-if="list.goodsStatus == 3" class="row cont-center pd_t_30 pd_b_30 yh_bd_bottom">
          <div class="font-28 col-666 flex-1">优惠</div>
          <div class="row cont-center">
            <div class="font-28 col-FF6251 pd_r_10">-￥{{(current.price - current.groupPrice).toFixed(2)}}</div>
						<div class="font-22 col-fff bg-FF6251 pd_l_10 pd_r_10">拼团优惠</div>
          </div>
        </div>
        <!-- 优惠券 -->
        <div class="row cont-center pd_t_30 pd_b_30 yh_bd_bottom">
          <div class="font-28 col-666">优惠券</div>
          <div class="font-28 pd_r_10 col-FF6251 color-active flex-1" v-if="haveCoupon || coupon"
               @click="toSelect()" style="display: flex;align-items: center">
            <div class="flex-1 align-right">{{coupon ? '-￥' + couponMoney : '点击选择'}}</div>
            <u-icon size="28" name="arrow-right" color="#2A6AAA"></u-icon>
          </div>
          <div class="font-28 col-666 pd_r_10 flex-1" v-if="!haveCoupon && !coupon" @click="toSelect()" style="display: flex;align-items: center">
            <div class="flex-1 align-right">暂无可用优惠券</div>
            <u-icon size="28" name="arrow-right" color="#666"></u-icon>
          </div>
        </div>

        <div class="row cont-center pd_t_30 pd_b_30">
          <div class="font-28 col-333 flex-1">应付总额</div>
          <div v-if="list.goodsStatus == 1" class="font-28 font-b col-FF6251 pd_r_10">
						￥{{coupon ? subtracts(current.price, couponMoney) : current.price}}
					</div>
					<div v-if="list.goodsStatus == 2" class="font-28 font-b col-FF6251 pd_r_10">
						￥{{coupon ? subtracts(current.discountsPrice,couponMoney) : current.discountsPrice}}
					</div>
					<div v-if="list.goodsStatus == 3" class="font-28 font-b col-FF6251 pd_r_10">
						￥{{coupon ? subtracts(current.groupPrice,couponMoney) : current.groupPrice}}
					</div>
        </div>
      </div>
    </view>
    <div class="bg-fff btn-container pd_t_19 pd_b_20">
      <u-button type="primary" :custom-style="customStyle" shape="circle" @click="submitOrder">提交订单</u-button>
    </div>
  </view>
</template>

<script>
  import {request} from "../../util/api";
  import {subtract, multiply, divide, add, TOAST} from "../../util/util";

  export default {
    onShow() {
      // 监听事件
      uni.$on('new_order', data => {
        this.list = data.list;
        this.current = data.current;
        if (data.userId) {
          this.shareUserId = data.userId
        }
        if (data.orderId) {
          this.mainOrder = data.orderId
        }
        if (data.coupon) {
          this.setCoupon(data.coupon)
        } else {
          setTimeout(() => {
            this.getCouponList()
          }, 310)
        }
      })

    },

    async mounted() {
      this.getAddress()
      const res = await this.getDictByType('giftName')
      if (res.length) {
        this.giftName = res[0].dictLabel
      }
    },

    onUnload() {
      // 移除监听事件
      uni.$off('new_order')
    },

    data() {
      return {
        banner: [],
				list: {},
				current: {},
				userId: '',
				coupon: '',
				couponMoney: 0,
				haveCoupon: false,

        customStyle: {
          background: '#1f476d',
          padding: '0 30rpx',
          color: '#fff'
        },
        shareUserId:'',
        mainOrder: '',
        userAddress: [],
        showAddress: '', //展示的地址信息（默认地址，或者第一个）
        giftName: ''
      }
    },

    methods: {
      async getDictByType(dictType) {
        if (!dictType) return []
        let res = await request({
          url: '/system/wx/dict/type/' + dictType,
          token: true,
        })
        return res.data
      },
      // 获取用户收货地址
      getAddress() {
        request({
          url: '/wx/getCompassUserAddressForUser',
          method: 'post'
        }).then(res => {
          this.userAddress = res.data.filter(item => item.disableFlag !== 0)
          if (this.userAddress.length) {
            let defaultAddress = this.userAddress.filter(item => {
              return item.isDefault
            })
            if (defaultAddress.length) {
              this.showAddress = defaultAddress[0]
            } else {
              this.showAddress = this.userAddress[0]
            }
          }
        })
      },

      subtracts(a, b) {
        return subtract(a, b)
      },

      setCoupon(data) {
        if (data.compassCoupon) {
          this.coupon = data
          var coupassCoupon = data.compassCoupon
          var goodsStatus = this.list.goodsStatus
          var panicBuyDiscountModel = this.list.panicBuyDiscountModel
          var couponMoney	= 0
          var oldMoney = this.current.price
          if (goodsStatus == 1 || goodsStatus == 3) {
            oldMoney = this.current.price
          } else if (goodsStatus == 2 && panicBuyDiscountModel == 2){
            oldMoney = this.current.discountsPrice
          } else if (goodsStatus == 2 && panicBuyDiscountModel == 1){
            oldMoney = this.current.fixedPrice
          }

          /*计算优惠券优惠的价格start*/
          // 折扣
          if (coupassCoupon.couponType == 1) {
            var val = subtract(1, divide(Number(coupassCoupon.discount_val), 10))
            couponMoney = multiply(oldMoney, val)
            // 满减
          } else {
            couponMoney = Number(coupassCoupon.discount)
          }
          /*计算优惠券优惠的价格end*/
          this.couponMoney  = couponMoney
        } else {
          this.coupon = ''
          this.couponMoney = 0
        }
      },

      getCouponList() {
        var that_ = this;
        request({
          url: '/app/coupon/get/couponList/' + that_.list.id  + '/and/' + that_.current.desc + '/by/' + that_.list.goodsStatus,
          method: 'post'
        }).then(ret => {
        	if (ret.data.canUseCoupons.length > 0) {
              that_.haveCoupon = true
            } else {
              that_.haveCoupon = false
            }
        })
      },

      toSelect() {
        setTimeout(() => {
          uni.$emit('new_order', {
            list: this.list,
            current: this.current,
            title: '1',
            coupon: this.coupon
          })
        }, 300)
        this.$u.route({
          url: '/pages/goods/select_coupon'
        })
      },

      submitOrder() {
        if (!this.showAddress) {
          TOAST('请选择地址信息！')
          return
        }
        var that_ = this;
        var orderMoney = that_.current.groupPrice;
        var discountMoney = subtract(that_.current.price, that_.current.groupPrice);
        var currentDataJson1 = JSON.parse(JSON.stringify(that_.current));
        var currentDataJson = JSON.stringify(currentDataJson1)

        if (this.coupon) {
          orderMoney = subtract(orderMoney, this.couponMoney)
          discountMoney = add(discountMoney, this.couponMoney)
        }
        var postData = {
          shareUserId: that_.shareUserId,
          goodsId: that_.list.id,
          goodsNum: '1',
          goodsName: that_.list.goodsName,
          goodsCover: that_.list.goodsCover,
          goodsStandard: currentDataJson,
          orderType: that_.list.goodsStatus,
          orderMoney: orderMoney.toFixed(2),
          discountMoney: discountMoney.toFixed(2),
          activityId: that_.list.activityId,
          mainOrder: that_.mainOrder,
          userAddressId: this.showAddress.id
        }

        request({
          url: '/app/goods/submitOrder',
          method: 'post',
          data: that_.coupon ? Object.assign(postData, {couponLogId: that_.coupon.id}) : postData
        }).then(ret => {
          var datas = ret.data;
          that_.openWindow(`/pages/goods/pay?orderMoney=${datas.orderMoney}&orderNum=${datas.orderNum}`)
        })
      },

      openWindow(path) {
        this.$u.route({
          url: path
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .goods_wrap {
    display: flex;
    flex-direction: column;
    height: 100%;
    .left-img {
      width: 160upx;
      height: 160upx;
      border-radius: 10upx;
    }

    .left-img img {
      width: 100%;
      height: 100%;
      border-radius: 10upx;
    }
  }
  .goods_page {
    background: #f7f7f7;
    flex: 1;
    padding-bottom: 120upx;
  }
  .btn-container {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    padding-left: 30upx;
    padding-right: 30upx;
    box-shadow: 1px 8px 16px 0px rgba(0, 0, 0, 0.47);
  }
</style>
